namespace Warehouse

open System
open System.Windows.Data
open System.Windows.Controls
open System.Windows
open Warehouse.Controls
open FSharp.Windows

type InventoryEvents = 
    | Edit
    | AdjustingQuantityPerUPC of EventWithValueAndCancel<int>
    | SeparateUpcToProduct
    | MergeUpcIntoAnotherProduct

type InventoryView(control) as this = 
    inherit PartialView<InventoryEvents, InventoryModel, InventoryControl>(control)

    let products = this.Control.ProductSearch.Products

    do
        products.SynchronizedWithCurrentItem()

    override this.EventStreams = 
        [
            products.DoubleClickRowEvent() |> Observable.mapTo Edit

            this.Control.UPCs.CellEditEnding 
                |> Observable.choose(fun event ->
                    match event.EditAction, event.EditingElement with
                    | DataGridEditAction.Commit, (:? TextBox as tb) 
                        when event.Column.Header = this.Control.UpcQuantityColumn.Header -> 
                            let value = int tb.Text
                            let cancel = fun() -> event.Cancel <- true
                            Some(AdjustingQuantityPerUPC(value, cancel))
                    | _ -> 
                        None
                )

            this.Control.SeparateUpc.ClickToValue SeparateUpcToProduct
            this.Control.MergeUpc.ClickToValue MergeUpcIntoAnotherProduct
        ]

    override this.SetBindings model = 
        Binding.FromExpression 
            <@ 
                this.Control.Brand.Text <- model.ProductSearch.SelectedProduct.ProductName.Brand.Name
                this.Control.ProductName.Text <- model.ProductSearch.SelectedProduct.ProductName.Name
                this.Control.SizeOrColor.Text <- model.ProductSearch.SelectedProduct.SizeOrColor
                this.Control.ShopCost.Text <- String.Format("{0:c}", model.ProductSearch.SelectedProduct.ShopCost)
                this.Control.Unit.Text <- model.ProductSearch.SelectedProduct.Unit.Name
                this.Control.SKU.Text <- string model.ProductSearch.SelectedProduct.SKU
                this.Control.UPCs.ItemsSource <- model.ProductSearch.SelectedProduct.UPCs
                this.Control.UPCs.SelectedItem <- model.SelectedUpc

                this.Control.SeparateUpc.IsEnabled <- model.IsSeparateEnable
                this.Control.MergeUpc.IsEnabled <- model.IsMergeEnable
            @>

            